clc; clear;

% 读取加密图像
enc_img = imread('encrypted_image_DNA.png');
[M, N] = size(enc_img);
len = M * N;

% CTBCS参数（与加密时保持一致）
r = 3.99; b = 30;
r1 = -10; b1 = -3; a = 1; b2 = 2*pi; c = 11.5;

% 初始值
x0 = 0.3; y0 = 0.5; z0 = 0.6;

% 图像像素转二进制字符串（加密图像）
enc_vec = uint8(enc_img(:));
enc_bin_str = dec2bin(enc_vec, 8)';
enc_bin_str = enc_bin_str(:)';  % 一维二进制字符串

% 加密DNA序列（二进制转DNA）
enc_dna_seq = bin2dna_rule1(enc_bin_str);

% 生成密钥序列DNA（长度同enc_dna_seq）
key_len = length(enc_dna_seq);
key_seq_vals = Sequence(key_len, x0, y0, z0, r, b, r1, b1, a, b2, c);
key_norm = mod(floor(abs(key_seq_vals)*1e6), 4);
key_dna_seq = int2dna(key_norm);

% DNA异或解密
dec_dna_seq = dna_xor(enc_dna_seq, key_dna_seq);

% DNA转二进制字符串
dec_bin_str = dna2bin_rule1(dec_dna_seq);

% 二进制字符串转像素值
dec_img_vec = uint8(bin2dec(reshape(dec_bin_str, 8, [])')');

% 重构解密图像
dec_img = reshape(dec_img_vec, M, N);

% 显示解密结果
figure; imshow(dec_img); title('DNA解密后的图像');

% ---- 函数定义同前 ----
function dna = bin2dna_rule1(bin_str)
    map = containers.Map({'00','01','10','11'}, {'A','C','G','T'});
    dna = '';
    for i=1:2:length(bin_str)
        pair = bin_str(i:i+1);
        dna = [dna map(pair)];
    end
end

function bin_str = dna2bin_rule1(dna_seq)
    map = containers.Map({'A','C','G','T'}, {'00','01','10','11'});
    bin_str = '';
    for i=1:length(dna_seq)
        bin_str = [bin_str map(dna_seq(i))];
    end
end

function dna_seq = int2dna(int_arr)
    bases = ['A','C','G','T'];
    dna_seq = bases(int_arr+1);
end

function res = dna_xor(dna1, dna2)
    map = containers.Map({'A','C','G','T'}, [0,1,2,3]);
    bases = ['A','C','G','T'];
    res = '';
    for i=1:length(dna1)
        v1 = map(dna1(i));
        v2 = map(dna2(i));
        v = bitxor(v1,v2);
        res = [res bases(v+1)];
    end
end
